local _M = {}
local utils = _M

--local json = require 'cjson.safe'


function _M.tableValToStr ( v )
    if "string" == type( v ) then
        v = string.gsub( v, "\n", "\\n" )
        if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
            return "'" .. v .. "'"
        end
        return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
    else
        return "table" == type( v ) and _M.tableToString( v ) or
            tostring( v )
    end
end

function _M.localTimeMs()
    local lt = ngx.localtime()
    local ms = string.format('%.3f', ngx.now())
    local t_str = string.format('%s,%s', lt, string.sub(ms, 12))
    return t_str
end

function _M.tableKeyToStr ( k )
    if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
        return k
    else
        return "[" .. _M.tableValToStr( k ) .. "]"
    end
end

function _M.tableToString( tbl )
    local result, done = {}, {}
    for k, v in ipairs( tbl ) do
        table.insert( result, _M.tableValToStr( v ) )
        done[ k ] = true
    end
    for k, v in pairs( tbl ) do
        if not done[ k ] then
            table.insert( result,
                _M.tableKeyToStr( k ) .. "=" .. _M.tableValToStr( v ) )
        end
    end
    return "{" .. table.concat( result, "," ) .. "}"
end

function _M.deepcopy(ob)
    local seen = {}
    local function _copy(ob)
        if type(ob) ~= 'table' then
            return ob
        elseif seen[ob] then
            return seen[ob]
        end
        local new_table = {}
        seen[ob] = new_table
        for k, v in pairs(ob) do
            new_table[_copy(k)] = _copy(v)
        end
        return setmetatable(new_table, getmetatable(ob))
    end
    return _copy(ob)
end


function _M.isInTable(value, tbl)
    for _, v in ipairs(tbl) do
        if v == value then
            return true
        end
    end
    return false
end

function _M.tableIsNotEmpty(tbl)
    return type(tbl) == 'table' and tbl ~= nil and tbl ~= ngx.null and  _G.next(tbl) ~= nil
end

function _M.tableIsEmpty(tbl)
    return type(tbl) ~= 'table' or tbl == nil or tbl == ngx.null or _G.next(tbl) == nil
end

function _M.isNotEmpty(s)
    return s ~= nil and s ~= '' and s ~= ngx.null
end

function _M.isEmpty(s)
    return s == nil or s == '' or s == ngx.null
end

function _M.strSplit(inputstr, sep)
    if sep == nil then
        sep = "%s"
    end
    local t = {}
    local i = 1
    for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do
        t[i] = str
        i = i + 1
    end
    return t
end


return utils
